<route lang="json5" type="home">
{
  style: {
    navigationStyle: 'custom',
    // #ifdef MP-ALIPAY
    enablePullDownRefresh: false,
    'mp-alipay': {
      allowsBounceVertical: 'NO',
      transparentTitle: 'always',
      titlePenetrate: 'YES',
      defaultTitle: '',
    },
    // #endif
  },
}
</route>
<template>
  <CustomNavbar :title="query.id ? '修改书籍' : '新增书籍'" />
  <view class="container">
    <uni-forms class="form" ref="form" :modelValue="form" label-position="left">
      <uni-forms-item label="封面" name="bookAvatar">
        <view style="position: relative; left: 20%; align-items: center; text-align: center">
          <uni-file-picker
            ref="avaterPickerRef"
            :value="[{ name: form.bookName, extname: '', url: form.bookAvatar }]"
            limit="1"
            :del-icon="false"
            disable-preview
            :imageStyles="imageStyles"
            file-mediatype="image"
            @select="selectAvatar"
          ></uni-file-picker>
        </view>
      </uni-forms-item>
      <uni-forms-item label="书名" name="bookName">
        <uni-easyinput type="text" v-model="form.bookName" placeholder="请输入书名" />
      </uni-forms-item>
      <uni-forms-item label="作者" name="author">
        <uni-easyinput type="text" v-model="form.author" placeholder="请输入作者" />
      </uni-forms-item>
      <uni-forms-item label="描述" name="description">
        <uni-easyinput type="textarea" v-model="form.description" placeholder="请输入描述" />
      </uni-forms-item>
      <view class="bottom">
        <view class="submit" @click="submit">{{ query.id ? '修改' : '新建' }}</view>
      </view>
    </uni-forms>
  </view>
</template>

<script lang="ts" setup>
import CustomNavbar from '@/components/CustomNavbar.vue'
import { useBookStore } from '@/store/book'
import { addOrUpdateApi, bookInfoApi } from '@/service/book'
import { getEnvBaseUrl } from '@/utils'
import { useUserStore } from '@/store/user'
import { Book } from '@/types/book'
import { SearchTypeEnum } from '@/enums/SearchTypeEnum'

const bookRef = useBookStore()
const userRef = useUserStore()
let form = bookRef.book
let tmpAvatar = ''
const baseUrl = getEnvBaseUrl()

// 小组头像
const imageStyles = {
  width: 120,
  height: 120,
}

const query = defineProps<{
  id?: number
}>()

onLoad(async () => {
  uni.showLoading()

  if (query.id) {
    console.log('修改')
    const avatarRes = await uni.downloadFile({
      url: baseUrl + '/file/download?type=' + SearchTypeEnum.BOOK + '&param=' + query.id, // 仅为示例，并非真实的资源
      // filePath: wx.env.USER_DATA_PATH + '/111.png',
      header: {
        Authorization: userRef.userInfo.token,
      },
    })
    console.log('download', avatarRes.tempFilePath)
    tmpAvatar = avatarRes.tempFilePath

    const bookInfoRes = await bookInfoApi(query.id)
    console.log('bookInfoRes.data', bookInfoRes.data)
    bookRef.clearBook()
    bookRef.setBook(bookInfoRes.data)
    form.id = bookInfoRes.data.id
    form.bookName = bookInfoRes.data.bookName
    form.bookAvatar = bookInfoRes.data.bookAvatar
    form.author = bookInfoRes.data.author
    form.description = bookInfoRes.data.description
    form.userId = bookInfoRes.data.userId
    form.status = bookInfoRes.data.status
    console.log('form', form)
  } else {
    form = bookRef.initBook
    // bookRef.clearBook()
  }
  uni.hideLoading()
})

const selectAvatar = (ev) => {
  tmpAvatar = ev.tempFiles[0].image.location
  form.bookAvatar = ev.tempFiles[0].image.location
}

const submit = async () => {
  console.log('form', form)
  const addBookRes = await addOrUpdateApi(form)
  form = addBookRes.data
  const baseUrl = getEnvBaseUrl()
  uni.showLoading({ title: '修改中...' })
  const res = await uni.uploadFile({
    url: baseUrl + '/file/upload',
    filePath: tmpAvatar,
    name: 'file',
    formData: {
      type: 2,
      param: JSON.stringify(form),
    },
  })
  // form.bookAvatar = JSON.parse(res.data).data
  // form.bookAvatar = 'http://localhost:8091/file/image/book?imageName=book_avatar_23.png'
  if (query.id) {
    const bookOfListIndex = bookRef.bookList.findIndex((item) => item.id === query.id)
    console.log(bookOfListIndex)
    bookRef.spliceBook(bookOfListIndex, { ...form })
  } else {
    bookRef.addBook(form)
  }
  bookRef.clearBook()
  uni.hideLoading()
  uni.navigateBack()
  uni.showToast({ icon: 'none', title: query.id ? '修改成功' : '添加成功' })
}
</script>

<style lang="scss">
.container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  width: 90%;
  padding: 30rpx;
  margin-top: 30rpx;
}
.form {
  background-color: #ffffff;
}
.bottom {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  width: 100%;
  margin-top: 70rpx;
  > .submit {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    color: #fff;
    text-align: center;
    background: $main-color;
  }
}
</style>
